package cn.hdu.liang.ch01;

public class Cmd {
    boolean isRightFmt = true;
    boolean helpFlag;
    boolean versionFlag;
    String cpOption = "";
    String clazz;
    String[] args;

    public Cmd(String cmdLine) {
        parseCmd(cmdLine);
    }

    public void parseCmd(String[] args) {
        int index = 1;

        if(args.length < 2) {
            isRightFmt = false;
            return;
        }

        if(!args[0].equals("java")) {
            isRightFmt = false;
        } else {
            switch(args[1]) {
                case "-help":
                case "-?":
                    helpFlag = true;
                    break;
                case "-version":
                    versionFlag = true;
                    break;
                case "-cp":
                case "classpath":
                    if(args.length < 4) {
                        isRightFmt = false;
                    }
                    index = 4;
                    this.cpOption = args[2];
                    break;
            }

            this.clazz = args[index - 1];
            this.args = new String[args.length - index];
            System.arraycopy(args, index, this.args, 0, args.length - index);
        }
    }

    private void parseCmd(String cmdLine) {
        // 解析命令行参数,以单个或者多个空格分开
        // but 如果文件名中有空格也就分开了
        String[] cmdArgs = cmdLine.trim().split("\\s+");
        parseCmd(cmdArgs);
    }

    public void printUsage() {
        System.out.println("Usage: java [-options] class [args...]\n");
    }
}
